package org.bonorsoft.modules.control.controller;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.bonorsoft.common.api.vo.Result;
import org.bonorsoft.common.constant.CommonConstant;
import org.bonorsoft.common.system.query.QueryGenerator;
import org.bonorsoft.common.util.oConvertUtils;
import org.bonorsoft.modules.control.entity.Label;
import org.bonorsoft.modules.control.entity.Population;
import org.bonorsoft.modules.control.entity.TreeData;
import org.bonorsoft.modules.control.service.ICommonService;
import org.bonorsoft.modules.control.service.IHouseService;
import org.bonorsoft.modules.control.service.IInforService;
import org.bonorsoft.modules.control.service.IPopulationService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.bonorsoft.common.aspect.annotation.AutoLog;
import org.bonorsoft.common.system.base.controller.BonorController;
import org.bonorsoft.modules.control.util.PoliceImportUtil;
import org.bonorsoft.modules.control.vo.Otree;
import org.bonorsoft.modules.control.vo.PopulationVo;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

 /**
 * @Description: 实有人口信息
 * @Author: WilliamYe
 * @Date:   2021-03-04
 * @Version: V1.0
 */
@Slf4j
@Controller
@RequestMapping("/control/population")
public class PopulationController extends BonorController<Population, IPopulationService> {
    private String prefix = "control/population";

	@Autowired
	private IPopulationService populationService;

	@Autowired
	private IHouseService houseService;

	@Autowired
	private ICommonService commonService;

	 @Autowired
	 private IInforService inforService;

	 @Value(value = "${william.path.upload}")
	 private String uploadpath;

	/**
	*首页
	*/
	@RequiresPermissions("control:population:view")
    @GetMapping()
    public String index()
    {
     return prefix + "/population";
    }

	/**
	 * 分页列表查询
	 *
	 * @param population
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "实有人口信息-分页列表查询")
	@RequiresPermissions("control:population:list")
	@GetMapping(value = "/list")
	@ResponseBody
	public Result<?> queryPageList(Population population,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<Population> queryWrapper = QueryGenerator.initQueryWrapper(population, req.getParameterMap());
		Page<Population> page = new Page<Population>(pageNo, pageSize);
		IPage<PopulationVo> pageList = populationService.paging(page,queryWrapper);
		return Result.ok(pageList);
	}

	/**
	  * 实有人口
	  */
	 @GetMapping("/getPopulation")
	 public String getPopulation(@RequestParam(name = "dzbm") String dzbm,
								 @RequestParam(name = "ywlsh") String ywlsh,
								 ModelMap map){
		 map.put("ywlsh", ywlsh);
		 List<PopulationVo> populations = populationService.listing(new QueryWrapper<Population>().eq("dzbm", dzbm));
		 if(populations.size() > 0) map.put("populations", populations);
		 return "control/house/population";
	 }

	 /**
	  * 实有人口详细信息页面
	  */
	 @GetMapping("/detail/{id}")
	 public String detail(@PathVariable("id") String id,ModelMap map){
		 Population population = populationService.getById(id);
		 map.put("population",population);
		 map.put("photo", commonService.getPhoto(id));
		 map.put("labelNames","");
		 if(oConvertUtils.isNotEmpty(population.getBq())){
			 List<Label> labelList = populationService.getLabel(id);
			 StringJoiner joiner = new StringJoiner(",");
			 labelList.forEach(item -> joiner.add(item.getLabelName()));
			 map.put("labelNames", joiner.toString());
		 }
		 return prefix + "/detail";
	 }
	 /**
	  * 选择地址树
	  */
	 @GetMapping("/selectAddressTree")
	 public String selectAddressTree()
	 {
		 return prefix + "/tree";
	 }

	 /**
	  * 加载所有地址列表树
	  */
	 @GetMapping("/addressTreeData")
	 @ResponseBody
	 public List<Otree> treeData(HttpServletRequest req)
	 {
		 List<Otree> ztrees = inforService.selectTreeData(req,new TreeData().setDeptName(CommonConstant.OFFICE_KEY));
		 return ztrees;
	 }

    /**
    * 添加页面
    *
    */
    @GetMapping("/add/{id}")
    public String add(@PathVariable("id") String id, ModelMap map)
    {
     	map.put("house", houseService.getById(id));
		map.put("labelNames", "");
    	return prefix + "/add";
    }

	/**
	 * 添加
	 *
	 * @param population
	 * @return
	 */
	@AutoLog(value = "实有人口信息-添加")
	@RequiresPermissions("control:population:add")
	@PostMapping(value = "/add")
    @ResponseBody
	public Result<?> add(@Validated Population population, String photo) {
		String rkbm = UUID.randomUUID().toString().replaceAll("-", "");
		population.setRkbm(rkbm).setInTime(new Date()).setGxsj(new Date());
		populationService.save(population);
		if(oConvertUtils.isNotEmpty(photo)){
			commonService.addPhoto(rkbm, photo);
		}
		return Result.ok("添加成功！");
	}

    /**
    * 编辑页面
    */
	@GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap map) {
		Population population = populationService.getById(id);
		map.put("population", population);
		map.put("photo", commonService.getPhoto(id));
		map.put("labelNames","");
		if(oConvertUtils.isNotEmpty(population.getBq())){
			List<Label> labelList = populationService.getLabel(id);
			StringJoiner joiner = new StringJoiner(",");
			labelList.forEach(item -> joiner.add(item.getLabelName()));
			map.put("labelNames", joiner.toString());
		}
     	return prefix + "/edit";
    }

	/**
	 * 编辑
	 *
	 * @param population
	 * @return
	 */
	@AutoLog(value = "实有人口信息-编辑")
	@RequiresPermissions("control:population:edit")
	@PostMapping(value = "/edit")
	@ResponseBody
	public Result<?> edit(@Validated Population population,String photo) {
		population.setGxsj(new Date());
		populationService.updateById(population);
		if(oConvertUtils.isNotEmpty(photo)){
			commonService.updatePhoto(population.getRkbm(), photo);
		}
		return Result.ok("编辑成功!");
	}

	/**
	 * 通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "实有人口信息-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		populationService.removeById(id);
		return Result.ok("删除成功!");
	}

	/**
	 * 批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "实有人口信息-批量删除")
	@RequiresPermissions("control:population:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	@ResponseBody
	@Transactional
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		List<String> list = Arrays.asList(ids.split(","));
		this.populationService.removeByIds(list);
		commonService.removeByIds(list);
		return Result.ok("批量删除成功！");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "实有人口信息-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		Population population = populationService.getById(id);
		return Result.ok(population);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param population
    */
    @AutoLog(value = "实有人口信息-导出excel")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Population population) {
		// Step.1 组装查询条件
		QueryWrapper<Population> queryWrapper = QueryGenerator.initQueryWrapper(population, request.getParameterMap());
		// Step.2 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		List<PopulationVo> pageList = populationService.listing(queryWrapper);
		PoliceImportUtil.exportPopulationXls(pageList);
		// 导出文件名称
		mv.addObject(NormalExcelConstants.FILE_NAME, "实有人口信息");
		mv.addObject(NormalExcelConstants.CLASS, PopulationVo.class);
		ExportParams exportParams = new ExportParams("实有人口列表数据", "导出信息");
		exportParams.setImageBasePath(uploadpath);
		mv.addObject(NormalExcelConstants.PARAMS, exportParams);
		mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
		return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @AutoLog(value = "实有人口信息-通过excel导入数据")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    @ResponseBody
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			try {
				List<PopulationVo> list = ExcelImportUtil.importExcel(file.getInputStream(), PopulationVo.class, params);
				long start = System.currentTimeMillis();
				PoliceImportUtil.importPopulationSave(list);
				log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				return Result.ok("文件导入成功！数据行数：" + list.size());
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				return Result.error("文件导入失败:" + e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.error("文件导入失败！");
    }

    /**
     * 模板下载
     * @return
     */
    @AutoLog(value = "实有人口信息-模板下载", operateType = 6)
    @RequestMapping(value = "/importTemplate")
    public ModelAndView importTemplate() {
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, "实有人口信息模板"); //此处设置的filename无效 ,前端会重更新设置一下
		mv.addObject(NormalExcelConstants.CLASS, PopulationVo.class);
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("实有人口信息报表", "填报人:" + getLoginUserName(), "实有人口信息"));
		mv.addObject(NormalExcelConstants.DATA_LIST, new ArrayList<>());
		return mv;
    }

}
